<?php

namespace app\models;

use Yii;
use yii\base\Exception;
use yii\data\Pagination;
use yii\db\ActiveRecord;
use yii\db\Query;
use app\models\Card;


class Outbound extends ActiveRecord
{
    //public $title;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [


            ['orderno', 'required'],
            ['title','string'],
            ['order_id','string'],
            ['iccid_list', 'validatelist'],
            [['iccid_start', 'iccid_end'], 'validatesmall'],
            ['batch_no', 'string', 'max' => 32],
        ];
    }
    public function validatesmall($attribute, $params){
        if($this->iccid_start > $this->iccid_end){
            $this->addError($attribute, "开始号码不能大于结束号码.");
        }
        $a=substr($this->iccid_start,-5);
        $b=substr($this->iccid_end,-5);
        $small=$b-$a+1;
        if ($this->number != $small){
            $this->addError($attribute,"iccid数量不对");
        }

    }
    public function validatelist($attribute,$params){
        $str = str_replace(array("\r\n", "\r", "\n"), "", $this->iccid_list);
        $list = strlen($str) / 20;
        if($this->number != $list){
            $this->addError($attribute,"iccid数量错误");
        }
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [

            'rkd'     => '选择订单号',
            'rk_name' => '采购项目名称',
            'number'  => '数量',
            'iccid_list' => 'ICCID列表',
            'iccid_start' => 'ICCID开始号码',
            'iccid_end' => 'ICCID结束号码',
            'batch_no' => '批次号',
            'title' => '订单标题',
            'order_id' => '订单编号',
            'orderno' => '订单号',

        ];
    }



    /**
     * 关联套餐
     * @return \yii\db\ActiveQuery
     */
    public function getPackage()
    {
        return $this->hasOne(Package::class, ['id' => 'package_id']);
    }

    /**
     * 关联运营商
     * @return \yii\db\ActiveQuery
     */
    public function getIsp()
    {
        return $this->hasOne(Isp::class, ['id' => 'isp_id']);
    }
    /**
     * 关联订单标题
     * @return \yii\db\ActiveQuery
     */
    public function getOrder()
    {
        return $this->hasOne(Order::class, ['id' => 'order_id']);
    }
    /**
     * 生成新的批次号
     * @param integer $mid 管理用户编号，0表示系统自动添加
     * @return string
     */
    public static function generateBatchNo($mid = 0)
    {
        return date('YmdHis') . Util::randomStr(6) . $mid;
    }
    /**
     * 检查iccid
     */
    public function checkIccid($iccid_start='',$iccid_end='',$iccid_list='',$uid='',$agent='',$package_id='',$term_length='',$term_length_unit='',$number='',$amount=''){
        if(!empty($iccid_start) && !empty($iccid_end)){
            for ($i = 0; $i < strlen($iccid_start); $i++) {
                if ($iccid_start[$i] != $iccid_end[$i]) {
                    $prefix = substr($iccid_start, 0, $i);
                    $iccidList = range(substr($iccid_start, $i), substr($iccid_end, $i));
                    $chrLen = strlen(substr($iccid_start, $i));
                    foreach ($iccidList as $key=>$item) {
                        $iccid = $prefix . str_pad($item, $chrLen, '0', STR_PAD_LEFT);
                        $card = Card::find()->asArray()->where(['iccid' => $iccid])->one();
                        if (empty($card)) {
                            //Card::addError('iccid_list', 'ICCID【' . $iccid . '】不是有效的卡。');
                            return ['code'=>1001,'msg'=>'ICCID【' . $iccid . '】不是有效的卡。'];
                        }

                        if (!empty($card['uid']) || !empty($card['agent_id'])) {
                            return ['code'=>1001,'msg'=>'ICCID【' . $iccid . '】已经有分配的用户了。'];
                        }

                        $cardList[] = $card;
                        $cardData[$key]['id'] = $card['id'];
                        $cardData[$key]['iccid'] = $iccid;
                        $cardData[$key]['uid'] = $uid;
                        $cardData[$key]['agent_id'] = $agent;
                        $cardData[$key]['package_id'] = $package_id;
                        $cardData[$key]['dispatch_time'] = time();
                        $cardData[$key]['term_length'] = $term_length;
                        $cardData[$key]['term_length_unit'] = $term_length_unit;
                        $cardData[$key]['money'] = $amount/$number;
                    }

                    break;
                }
            }
            foreach($cardData as $ckey=>$cval){
                $cvaid= $cval["id"];
                $carddata['iccid']=$cval['iccid'];
                $carddata['uid']=$cval['uid'];
                $carddata['agent_id']=$cval['agent_id'];
                $carddata['package_id']=$cval['package_id'];
                $carddata['dispatch_time']=time();
                $carddata['term_length']=$cval['term_length'];
                $carddata['term_length_unit']=$cval['term_length_unit'];
                $carddata['money']=$cval['money'];
                $carddata['status']=3;
                //pr($cval);
                $res = (new Query())->createCommand()
                    //->update('card',['iccid','uid','agent_id','package_id','dispatch_time','term_length','term_length_unit','term_end_time'],['id'=>$cvaid],$carddata)
                    ->update('card',$carddata,['id'=>$cvaid])
                ->execute();
                if(!$res){
                    return ['code'=>1001,'msg'=>'ICCID【' . $cval['iccid'] . '】更新失败。'];
                    break;
                }
            }
            return ['code'=>1,'msg'=>''];;
        }elseif(!empty($iccid_list)){
            $iccidList = preg_split('/\s/',$iccid_list, -1, PREG_SPLIT_NO_EMPTY);

            foreach ($iccidList as $key=>$item){
                $card = Card::find()->asArray()->where(['iccid' => $item])->one();
                if (empty($card)) {
                    //Card::addError('iccid_list', 'ICCID【' . $iccid . '】不是有效的卡。');
                    return ['code'=>1001,'msg'=>'ICCID【' . $item . '】不是有效的卡。'];
                }

                if (!empty($card['uid']) || !empty($card['agent_id'])) {
                    return ['code'=>1001,'msg'=>'ICCID【' . $item . '】已经有分配的用户了。'];
                }

                $cardList[] = $card;
                $cardData[$key]['id'] = $card['id'];
                $cardData[$key]['iccid'] = $item;
                $cardData[$key]['uid'] = $uid;
                $cardData[$key]['agent_id'] = $agent;
                $cardData[$key]['package_id'] = $package_id;
                $cardData[$key]['dispatch_time'] = time();
                $cardData[$key]['term_length'] = $term_length;
                $cardData[$key]['term_length_unit'] = $term_length_unit;
                $cardData[$key]['money'] = $amount/$number;
            }
            foreach($cardData as $ckey=>$cval){
                $cvaid= $cval["id"];
                $carddata['iccid']=$cval['iccid'];
                $carddata['uid']=$cval['uid'];
                $carddata['agent_id']=$cval['agent_id'];
                $carddata['package_id']=$cval['package_id'];
                $carddata['dispatch_time']=time();
                $carddata['term_length']=$cval['term_length'];
                $carddata['term_length_unit']=$cval['term_length_unit'];
                $carddata['money']=$cval['money'];
                $carddata['status']=3;
                $res = (new Query())->createCommand()
                    ->update('card',$carddata,['id'=>$cvaid])
                    ->execute();
                if(!$res){
                    return ['code'=>1001,'msg'=>'ICCID【' . $cval['iccid'] . '】更新失败。'];
                    break;
                }
            }
            return ['code'=>1,'msg'=>''];

        }
    }


}

